package com.yswee.mallnavi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.ys.rkapi.MyManager;
import com.yswee.framework.data.BaseArrayData;
import com.yswee.framework.data.parser.IParser;
import com.yswee.framework.manager.ActivityManager;
import com.yswee.framework.net.http.Callback;
import com.yswee.framework.net.http.Entity;
import com.yswee.framework.utils.StringUtils;
import com.yswee.framework.utils.ViewInject;
import com.yswee.framework.widget.MToast;
import com.yswee.framework.widget.switchtab.SwitchDotBar;
import com.yswee.mallnavi.R;
import com.yswee.mallnavi.activity.base.CardActivity;
import com.yswee.mallnavi.activity.version.UpgradeActivity;
import com.yswee.mallnavi.context.ContextConstant;
import com.yswee.mallnavi.entity.common.AdsEntity;
import com.yswee.mallnavi.entity.common.VersionEntity;
import com.yswee.mallnavi.entity.home.NavEntity;
import com.yswee.mallnavi.model.common.CommonModel;
import com.yswee.mallnavi.model.home.HomeModel;
import com.yswee.mallnavi.service.CoreService;
import com.yswee.mallnavi.view.screensaver.AdsItem;

import java.util.ArrayList;

public class MainActivity extends CardActivity {

    private final static int MAXVIEWPAGERITEM = 3;
    private final static int MSGWHAT_ADS = 0;
    private final static int MSGWHAT_BANNER = 1;
    private final static int MSGDELAY_BANNER = (5 * 60 + 5) * 1000;
    private final static int MSGWHAT_NAVS = 2;
    private final static int MSGDELAY_NAVS = (5 * 60 + 10) * 1000;

    private static final int MSGWHAT_VERSION = 3;
    private static final int MSGDELAY_VERSION = 5 * 60 * 1000;

    @ViewInject
    private ViewPager uvcontainer;
    @ViewInject
    private SwitchDotBar uvdotbar;
    @ViewInject
    private ImageView imgnav0;
    @ViewInject
    private ImageView imgnav1;
    @ViewInject
    private ImageView imgnav2;
    @ViewInject
    private ImageView imgnav3;
    @ViewInject
    private ImageView imgnav4;
    @ViewInject
    private ImageView imgnav5;

    private HomeModel mHomeModel;
    private CommonModel mCommonModel;
    private ArrayList<AdsEntity> mDataArray;

    private AdsItem[] viewList;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSGWHAT_VERSION:
                    checkVersion(true);
                    break;

                case MSGWHAT_BANNER:
                    getBannerList();
                    break;

                case MSGWHAT_NAVS:
                    getNavList();
                    break;

                case MSGWHAT_ADS:
                    int index = uvcontainer.getCurrentItem();
                    index++;
                    if (index >= mDataArray.size()) {
                        index = 0;
                    }
                    uvcontainer.setCurrentItem(index, true);
                    break;
            }
        }
    };

    private PagerAdapter mPagerAdapter = new PagerAdapter() {
        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        @Override
        public int getCount() {
            return mDataArray != null ? mDataArray.size() : 0;
        }

        @Override
        public Object instantiateItem(View container, int position) {
            if (viewList == null) {
                viewList = new AdsItem[MAXVIEWPAGERITEM];
            }
            AdsItem view = viewList[position % viewList.length];
            if (view == null) {
                view = new AdsItem(MainActivity.this);
                viewList[position % viewList.length] = view;
            }
            if (view.getParent() == null) {
                ((ViewPager) container).addView(view);
            }
            ((ViewPager) container).requestLayout();
            view.setDataSource(mDataArray.get(position));
            view.setTag(position);
            return view;
        }

        @Override
        public void destroyItem(View container, int position, Object object) {

        }
    };

    @Override
    protected boolean getAutoLoading() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityManager.get().popupAllActivityBeforeThis(this);
        /*if (Application.get().getAppConfigure().getIsDebug()) {
            showToastMessage(WindowManager.get().getScreenWidth() + "*" +
                    WindowManager.get().getScreenHeight() + "," +
                    "dpi-" + WindowManager.get().getDensityDpi() + "," +
                    "ppi-" + WindowManager.get().getDensityPpiX() + "*" +
                             WindowManager.get().getDensityPpiY() + "," +
                    "smalldpi-" + WindowManager.get().getSmallwidthDensityDp() + "dp",
                    Toast.LENGTH_LONG);
        }*/
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected void onBindListener() {
        super.onBindListener();
        View.OnClickListener imgclick = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (view.getTag() != null && view.getTag() instanceof NavEntity) {
                    NavEntity nav = (NavEntity) view.getTag();
                    nav.gotoIntentPage(MainActivity.this);
                }
            }
        };
        imgnav0.setOnClickListener(imgclick);
        imgnav1.setOnClickListener(imgclick);
        imgnav2.setOnClickListener(imgclick);
        imgnav3.setOnClickListener(imgclick);
        imgnav4.setOnClickListener(imgclick);
        imgnav5.setOnClickListener(imgclick);
        uvcontainer.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                try {
                    AdsItem view = viewList[position % viewList.length];
                    view.setDataSource(mDataArray.get(position));
                    uvdotbar.setDatas(mDataArray.size(), position);
                } catch (Exception e) {

                }
            }

            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {
                switch (state) {
                    case ViewPager.SCROLL_STATE_DRAGGING:
                        mHandler.removeCallbacksAndMessages(null);
                        break;

                    case ViewPager.SCROLL_STATE_IDLE:
                        int index = uvcontainer.getCurrentItem();
                        int delay = mDataArray.get(index).getIntervalTime();
                        mHandler.sendEmptyMessageDelayed(MSGWHAT_ADS, delay);
                        break;

                    default:
                        break;
                }
            }
        });
        tvversion.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                checkVersion(false);
                return true;
            }
        });
    }

    @Override
    protected void onApplyData() {
        super.onApplyData();
        uvtopbar.setHandleClick(true);
        checkVersion(true);
        startService(new Intent(MainActivity.this, CoreService.class));
        initializeManager();
    }

    @Override
    public void onApplyLoadingData() {
        getBannerList();
        getNavList();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacksAndMessages(null);
    }

    private void getBannerList() {
        if(mCommonModel == null) {
            mCommonModel = new CommonModel(this);
        }
        mCommonModel.getBannerList(new Callback<BaseArrayData<AdsEntity>>() {
            @Override
            public void onFinish(Entity<BaseArrayData<AdsEntity>> entity) {
                IParser<BaseArrayData<AdsEntity>> parser = entity.getParser();
                final BaseArrayData<AdsEntity> data = entity.getParsedData();
                if(parser.getIsOk() && data != null && data.getArray() != null) {
                    mDataArray = data.getArray();
                    applyBannerInfo();
                    return;
                }
                String msg = entity.getMessage();
                if(StringUtils.isEmpty(msg)) {
                    msg = getResources().getString(R.string.home_banner_fail);
                }
                MToast.showToastMessage(msg);
            }

            @Override
            public void onError(Entity<BaseArrayData<AdsEntity>> entity) {
                if(entity.getEntityStatus() != Entity.NETINVALID) {
                    MToast.showToastMessage(R.string.home_banner_fail);
                }
            }
        });
        mHandler.sendEmptyMessageDelayed(MSGWHAT_BANNER, MSGDELAY_BANNER);
    }

    private void applyBannerInfo() {
        if (mDataArray != null && mDataArray.size() > 0) {
            uvdotbar.setDatas(mDataArray.size(), 0);
            uvcontainer.setAdapter(mPagerAdapter);
            if (viewList != null && viewList.length > 0 && viewList[0] != null) {
                viewList[0].setDataSource(mDataArray.get(0));
            }
            mHandler.removeCallbacksAndMessages(null);
            int index = uvcontainer.getCurrentItem();
            int delay = mDataArray.get(index).getIntervalTime();
            mHandler.sendEmptyMessageDelayed(MSGWHAT_ADS, delay);
        } else {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    private void getNavList() {
        if(mHomeModel == null) {
            mHomeModel = new HomeModel(this);
        }
        mHomeModel.getNavs(new Callback<BaseArrayData<NavEntity>>() {
            @Override
            public void onFinish(Entity<BaseArrayData<NavEntity>> entity) {
                IParser<BaseArrayData<NavEntity>> parser = entity.getParser();
                final BaseArrayData<NavEntity> data = entity.getParsedData();
                if(parser.getIsOk() && data != null && data.getArray() != null) {
                    applyNavInfo(data.getArray());
                    return;
                }
                String msg = entity.getMessage();
                if(StringUtils.isEmpty(msg)) {
                    msg = getResources().getString(R.string.home_navs_fail);
                }
                MToast.showToastMessage(msg);
            }

            @Override
            public void onError(Entity<BaseArrayData<NavEntity>> entity) {
                if(entity.getEntityStatus() != Entity.NETINVALID) {
                    MToast.showToastMessage(R.string.home_navs_fail);
                }
            }
        });
        mHandler.sendEmptyMessageDelayed(MSGWHAT_NAVS, MSGDELAY_NAVS);
    }

    private void applyNavInfo(ArrayList<NavEntity> array) {
        if (array != null && array.size() > 0) {
            for (int i = 0; i < array.size(); i++) {
                NavEntity nav = array.get(i);
                ImageView imageview = null;
                if (nav.displayOrder == 1) {
                    imageview = imgnav0;
                } else if (nav.displayOrder == 2) {
                    imageview = imgnav1;
                } else if (nav.displayOrder == 3) {
                    imageview = imgnav2;
                } else if (nav.displayOrder == 4) {
                    imageview = imgnav3;
                } else if (nav.displayOrder == 5) {
                    imageview = imgnav4;
                } else if (nav.displayOrder == 6) {
                    imageview = imgnav5;
                }
                if (imageview != null) {
                    imageview.setTag(nav);
                    final ImageView imageview_f = imageview;
                    Glide.with(MainActivity.this)
                            .load(nav.pic)
                            .into(imageview);
                }
            }
        }
    }

    private void checkVersion(final boolean silent) {
        if(mCommonModel == null) {
            mCommonModel = new CommonModel(this);
        }
        mCommonModel.getVersion(new Callback<VersionEntity>() {
            @Override
            public void onFinish(Entity<VersionEntity> entity) {
                IParser<VersionEntity> parser = entity.getParser();
                if(parser.getIsOk()) {
                    final VersionEntity version = entity.getParsedData();
                    if(version != null) {
                        if(version.hasNewVersion()) {
                            Intent intent = new Intent(MainActivity.this, UpgradeActivity.class);
                            intent.putExtra(ContextConstant.INTENT_DATA, version);
                            startActivity(intent);
                        } else {
                            if (!silent) {
                                showToastMessage(R.string.checkversion_succ);
                            }
                        }
                        return;
                    }
                    if (!silent) {
                        showToastMessage(R.string.checkversion_err);
                    }
                }
            }

            @Override
            public void onError(Entity<VersionEntity> entity) {
                if (!silent) {
                    showToastMessage(R.string.checkversion_err);
                }
            }
        });
        mHandler.sendEmptyMessageDelayed(MSGWHAT_VERSION, MSGDELAY_VERSION);
    }

    private void initializeManager() {
        try {
            final MyManager manager = MyManager.getInstance(this);
            manager.bindAIDLService(MainActivity.this);
            manager.setConnectClickInterface(new MyManager.ServiceConnectedInterface() {
                @Override
                public void onConnect() {
                    ContextConstant.SERIALNO = manager.getSn();
                }
            });
        } catch (Exception e) {
            MToast.showToastMessage("初始化失败:" + e.getMessage());
        }
    }

}
